package com.elementum.olegomatic.dictionaries.impl;

import com.elementum.olegomatic.dictionaries.DictId;
import com.elementum.olegomatic.dictionaries.Dictionary;
import com.elementum.olegomatic.dictionaries.DictionaryFactory;
import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import org.apache.log4j.Logger;

import java.net.UnknownHostException;
import java.util.Iterator;

/**
 * Created with IntelliJ IDEA.
 * User: jmp
 * Date: 10/9/13
 * Time: 7:17 PM
 * To change this template use File | Settings | File Templates.
 */
public class DictionaryFactoryImpl implements DictionaryFactory {
    private static final Logger LG = Logger.getLogger(DictionaryFactoryImpl.class);

    @Override
    public Dictionary getDictionary(DictId id) {
        Dictionary r = new DictionaryImpl();
        try {
            MongoClient mongoClient = new MongoClient( "labs-nodejs.elementums.com" , 27017 );
            DB db = mongoClient.getDB( "elementum_labs" );
//            boolean auth = db.authenticate("admin", "elementum_lab");
            DBCollection coll = db.getCollection(id.getMongoCollection());
            DBObject query = id.getQuery();
            LG.error(query.toString());
            AggregationOutput all = null;
            if(query instanceof BasicDBObject) {
                all = coll.aggregate(query);
            } else if (query instanceof BasicDBList) {
                BasicDBList l = (BasicDBList) query;
                DBObject first = (DBObject) l.get(0);
                DBObject[] rest = new DBObject[l.size()-1];
                for (int idx = 1; idx < l.size();idx++) {
                    rest[idx-1] = (DBObject) l.get(idx);
                }
                all = coll.aggregate(first, rest);
            }
            Iterable<DBObject> it = all.results();
            for(DBObject dbo : it) {
                r.add((String) dbo.get("keyword"));
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            throw new RuntimeException("Can't open DB Connection.", e);
        }
        return r;
    }
}
